package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.controller.UserController;
import com.example.demo.entity.User;
import com.example.demo.exception.MyException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.PasswordUtils;
import com.example.demo.utils.ValidateCodeUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.dto.CustomerServiceConnection;
import com.example.demo.exception.ConnectionNotFound;
import com.example.demo.mapper.CustomerMapper;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final CustomerMapper customerMapper;

    // 简历客服与客户的绑定关系
    private static final Map<String,String> userToAgentMap = new ConcurrentHashMap<>();

    @Autowired
    public UserServiceImpl(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }

    @Override
    public User getUserById(int id){
        return getById(id);
    }

    @Override
    public User login(String phone, String password) throws MyException {
        if(phone == null || phone.isBlank()) {
            throw new MyException("手机号码不能为空");
        }
        if(phone.length() != 11){
            throw new MyException("非法手机号码");
        }
        if(password == null || password.isBlank()){
            throw new MyException("密码不能为空");
        }
        User user = baseMapper.selectByPhone(phone);
        if (user == null) {
            //System.out.println("没查到哈哈哈");
            throw new MyException("没查到哈哈哈");
        }
        if("禁用".equals(user.getStatus())){
            throw new MyException("账户已被锁定");
        }
        //System.out.println(PasswordUtils.encryptPassword(password) + "====" + user.getPassword());
        return baseMapper.selectByPhoneAndPassword(phone,PasswordUtils.encryptPassword(password));
    }

    @Override
    @Transactional
    public boolean logout(int userId) {
        // 更新用户最后活跃时间为退出时间
        return true;
    }

    @Override
    public Integer sendMsg(String phone) throws MyException {
        if(phone == null || phone.isBlank()) {
            throw new MyException("手机号码不能为空");
        }
        if(phone.length() != 11){
            throw new MyException("非法手机号码");
        }
        User user = baseMapper.selectByPhone(phone);
        if(user == null) {
            // 账户未注册, 注册账户
            user = new User();
            user.setPhoneNumber(phone);
            baseMapper.insert(user);
            // 号码为注册, 更新标识
            ValidateCodeUtils.flag = false;
        }
        return ValidateCodeUtils.generateValidateCode(6);
    }

    @Override
    public User checkMsg(String phone, Integer code) throws MyException {
        if(code == null){
            throw new MyException("验证码不能为空");
        }
        if(phone == null || phone.isBlank()){
            throw new MyException("手机号码不能为空");
        }
        if(phone.length() != 11){
            throw new MyException("非法手机号码");
        }
        User user = baseMapper.selectByPhone(phone);
        if("禁用".equals(user.getStatus())){
            throw new MyException("账户已被锁定");
        }
        // 检查codeMap中的验证码与前台提交的验证码是否一致
        boolean flag = code.equals(ValidateCodeUtils.codeMap.get(phone));
        return flag ? baseMapper.selectByPhone(phone) : null;
    }

    @Override
    public boolean revokeAccount(String phone, Integer code) throws MyException {
        if(code == null){
            throw new MyException("验证码不能为空");
        }
        if(phone == null || phone.isBlank()){
            throw new MyException("手机号码不能为空");
        }
        if(phone.length() != 11){
            throw new MyException("非法手机号码");
        }
        // 检查session中的验证码与前台提交的验证码是否一致
        if(code.equals(ValidateCodeUtils.codeMap.get(phone))){
            return baseMapper.revokeUserByPhone(phone);
        }
        return false;
    }


    @Override
    public boolean changePassword(Integer userId, String newPassword, String phone, Integer code) throws MyException {
        if(newPassword == null || newPassword.isBlank()){
            throw new MyException("新密码不能为空");
        }
        if(code == null){
            throw new MyException("验证码不能为空");
        }

        // 验证码校验
        boolean flag = code.equals(ValidateCodeUtils.codeMap.get(phone));

        // 计算距离上一次修改密码的时间
        LocalDateTime start = PasswordUtils.passwordTime.get(userId);
        LocalDateTime end = LocalDateTime.now();
        long hours = 100;
        // 防止start为空
        if(start != null){
            hours = Duration.between(start, end).toHours();
        }

        if(!flag){
            throw new MyException("验证码错误");
        } else if(hours<24){
            // 更新status字段,锁定账户
            User user = new User();
            user.setId(userId);
            user.setStatus("禁用");
            baseMapper.updateById(user);
            throw new MyException("频繁操作，您的账户将被锁定");
        }else{
            // 加密新密码并更新
            String encodedNewPassword = PasswordUtils.encryptPassword(newPassword);
            int count = baseMapper.updatePasswordById(userId, encodedNewPassword);
            System.out.println(count);
            if(count > 0){
                // 更新最后修改密码的时间
                PasswordUtils.passwordTime.put(userId,end);
                return true;
            }
        }
        return false;
    }



    @Override
    @Transactional
    public User getUserProfile(int userId) {
        // 查询用户资料时排除密码字段
        User user = getById(userId);
        if (user != null) {
            user.setPassword(null);
        }

        //baseMapper.updateLastActiveTimeById(userId, LocalDateTime.now());
        return user;
    }

    @Override
    @Transactional
    public boolean updateUserHead(int userId, String headUrl) {
        //baseMapper.updateLastActiveTimeById(userId, LocalDateTime.now());
        return baseMapper.updateHeadById(userId, headUrl) > 0;
    }

    @Override
    @Transactional
    public boolean updateUserInfo(int userId, String nickname, String gender, Integer age, String email) {
        //baseMapper.updateLastActiveTimeById(userId, LocalDateTime.now());
        return baseMapper.updateUserInfoById(userId, nickname, gender, age, email) > 0;
    }

    @Override
    @Transactional
    public boolean changePassword(int userId, String oldPassword, String newPassword) {
        // 查询用户信息
        User user = getById(userId);
        if (user == null) {
            return false;
        }

        // 验证旧密码(使用自定义工具类)
        if (!PasswordUtils.verifyPassword(oldPassword, user.getPassword())) {
            return false;
        }

        // 加密新密码并更新
        String encodedNewPassword = PasswordUtils.encryptPassword(newPassword);

        //baseMapper.updateLastActiveTimeById(userId, LocalDateTime.now());
        return baseMapper.updatePasswordById(userId, encodedNewPassword) > 0;
    }

    @Override
    public boolean encryptUserPassword(int userId, String password){
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        if (user.getPassword().equals(password)) {
            // 加密新密码并更新
            String encodedNewPassword = PasswordUtils.encryptPassword(password);

            return baseMapper.updatePasswordById(userId, encodedNewPassword) > 0;
        }
        return false;
    }

    @Override
    public CustomerServiceConnection getCustomerServiceConnection() throws ConnectionNotFound {
        List<CustomerServiceConnection> customerServiceConnections = customerMapper.findAll();
        if (customerServiceConnections == null || customerServiceConnections.isEmpty()) {
            throw new ConnectionNotFound("暂无空闲客服！");
        }

        return customerServiceConnections.get(0);
    }

    @Override
    public CustomerServiceConnection getCustomerServiceConnection(String userId) throws ConnectionNotFound {
        // 先查绑定
        if (userToAgentMap.containsKey(userId)) {
            String agentId = userToAgentMap.get(userId);
            // 你需要根据agentId查找客服信息
            return customerMapper.findById(agentId);
        }
        // 没有绑定则分配
        List<CustomerServiceConnection> customerServiceConnections = customerMapper.findAll();
        if (customerServiceConnections == null || customerServiceConnections.isEmpty()) {
            throw new ConnectionNotFound("暂无空闲客服！");
        }
        CustomerServiceConnection assigned = customerServiceConnections.get(0);
        System.out.println("空？" + assigned);
        userToAgentMap.put(userId, assigned.getAgentId()); // 绑定
        return assigned;
    }



}
